package fun.ticsmyc.question.stringQuestion;

/**
 * @author Ticsmyc
 * @package fun.ticsmyc.question.stringQuestion
 * @date 2021-02-19 16:32
 */
public class 大数加法和乘法 {
    /**
     * 字符串乘法
     * @param num1
     * @param num2
     * @return
     */
    public String multiply(String num1, String num2) {
        String res ="0";
        char[] str = num2.toCharArray();
        int cnt =0;
        for(int i=str.length-1;i>=0;--i){
            res = add(res,multi(num1,(int)(str[i]-'0'),cnt++));
        }
        return res;
    }

    // a*b  后面补cnt个0
    public String multi(String a,int b, int cnt){
        if(b==0 || a.equals("0")){
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<cnt;++i){
            sb.append('0');
        }
        char[] str =a.toCharArray();
        int i=str.length-1;
        int jinwei =0;
        while(i>=0){
            int cur = (int)(str[i]-'0')*b+jinwei;
            jinwei = cur/10;
            cur =cur %10;
            sb.append(cur);
            i--;
        }
        if(jinwei !=0){
            sb.append(jinwei);
        }
        return sb.reverse().toString();

    }

    /**
     * 字符串加法
     * @param a
     * @param b
     * @return
     */
    public String add(String a,String b){
        char[] str1= a.toCharArray();
        char[] str2 = b.toCharArray();
        StringBuilder sb = new StringBuilder();
        int i1 =str1.length-1;
        int i2 = str2.length-1;
        int jinwei =0;
        while(i1 >=0 && i2>=0){
            int cur = (int)(str1[i1]-'0')+(int)(str2[i2]-'0')+jinwei;
            jinwei = cur/10;
            cur = cur%10;
            sb.append(cur);
            i1--;
            i2--;
        }
        while(i1>=0){
            int cur = (int)(str1[i1]-'0')+jinwei;
            jinwei = cur/10;
            cur = cur%10;
            sb.append(cur);
            i1--;
        }
        while(i2>=0){
            int cur = (int)(str2[i2]-'0')+jinwei;
            jinwei = cur/10;
            cur = cur%10;
            sb.append(cur);
            i2--;
        }
        if(jinwei !=0){
            sb.append(jinwei);
        }
        return sb.reverse().toString();
    }
}
